<?php

#namespace Giocondo;

# string -- translate, convert and quote strings for output.
class String {
	# Convert and quote percent and non percent strings.
	# Suitable for element content or JavaScript code.
	# TODO: default value for filters should be the most commonly used.
	# At last make a count of each uses and change it.
	static public function filter($text, $filters = 'nj') {
		if (strpos($filters, 'p') !== FALSE) {
			$filters .= 'n';	# p implies n.
			# Translate percent strings, that is  strings with a special meaning, 
			# into non percent string, that is without special meaning.
			# TODO: problema stringa vuota
			if ($text[0] == '%') {
				# TODO: Put most common string types first to optimize.
				switch ($text[1]) {
					case '<':
						# Markup string
						$text = substr($text, 2);
						$filters .= 'h';
					break;

					case '!':
						# Simple string
						$text = substr($text, 2);
					break;

					case '%':
						# Simple string starting with %
						$text = substr($text, 1);
					break;
				}
			}
		}

		if (strpos($filters, 'h') === FALSE) {
			$text = htmlspecialchars($text, ENT_NOQUOTES);
		}

		if (strpos($filters, 'n') !== FALSE) {
			# TODO: what about using nl2br? Test the differences.
			$text = str_replace(array("\n", "\r"), array('<br />', '<br />'), $text);
		}

		if (strpos($filters, 'j') !== FALSE) {
			# / must be escaped for a markup string. See 
			# http://www.w3.org/TR/html401/appendix/notes.html#notes-specifying-data
			# Double quotes are not escaped because of the convention of always use 
			# single quotes around JavaScript strings.
			# Other JavaScript escape sequences are \t \b \v \f \0 and are not 
			# supported here (no escaping is performed for that codes, they are 
			# passed as they are). Among all these only \b (backspace) escape 
			# sequence is unknown to PHP and must be expressed in hex (or octal) 
			# notation \x8 or \10.
			$text = addcslashes($text, "'\\/\n\r");
		}

		return $text;
	}

	# Convert non percent strings. Suitable for element attributes.
	static public function attribute($text) {
		# Better to avoid line breaks within attribute values.
		# See http://www.w3.org/TR/xhtml1/guidelines.html#C_5
		return htmlspecialchars(str_replace(
			array("\n", "\r"), array(' ', ' '), $text)
		);
	}
}

# End of file
# vim: set ts=2 sw=2 noet:
?>
